package com.appcloner.ui.cloner

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.appcloner.data.model.InstalledApp
import com.appcloner.data.repository.ClonerRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

data class AppClonerUiState(
    val appInfo: InstalledApp? = null,
    val cloneName: String = "",
    val isLoading: Boolean = false,
    val isCreating: Boolean = false,
    val error: String? = null,
    val isSuccess: Boolean = false
)

@HiltViewModel
class AppClonerViewModel @Inject constructor(
    private val clonerRepository: ClonerRepository
) : ViewModel() {
    
    private val _uiState = MutableStateFlow(AppClonerUiState())
    val uiState: StateFlow<AppClonerUiState> = _uiState.asStateFlow()
    
    fun loadAppInfo(packageName: String) {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true) }
            
            try {
                val appInfo = clonerRepository.getAppInfo(packageName)
                _uiState.update { 
                    it.copy(
                        appInfo = appInfo,
                        isLoading = false
                    ) 
                }
            } catch (e: Exception) {
                _uiState.update { 
                    it.copy(
                        error = e.message ?: "加载应用信息失败",
                        isLoading = false
                    ) 
                }
            }
        }
    }
    
    fun onCloneNameChange(newName: String) {
        _uiState.update { it.copy(cloneName = newName, error = null, isSuccess = false) }
    }
    
    fun createClone() {
        viewModelScope.launch {
            _uiState.update { it.copy(isCreating = true, error = null) }
            
            try {
                val success = clonerRepository.createClone(
                    packageName = uiState.value.appInfo?.packageName ?: "",
                    cloneName = uiState.value.cloneName
                )
                
                if (success) {
                    _uiState.update { it.copy(isSuccess = true, isCreating = false) }
                } else {
                    _uiState.update { 
                        it.copy(
                            error = "创建分身失败",
                            isCreating = false
                        ) 
                    }
                }
            } catch (e: Exception) {
                _uiState.update { 
                    it.copy(
                        error = e.message ?: "创建分身时发生错误",
                        isCreating = false
                    ) 
                }
            }
        }
    }
}
